package oauth

import (
	"context"
	"micro-oauth/datamodels/autherror"
	"micro-oauth/datamodels/enum"
	"micro-oauth/datamodels/params"
)

type HomePageScopeResponse struct {
	ScopeId   uint64 `json:"scope_id"`
	ScopeName string `json:"scope_name"`
	ClientId  string `json:"client_id"`
}

func (s *OauthServiceImpl) ListHomePageScope(ctx context.Context, partnerId uint64) ([]*HomePageScopeResponse, autherror.HexError) {
	if partnerId == 0 {
		return nil, autherror.InvalidData("must specific partner id")
	}

	// get all scope
	scopeListReq := &params.ScopeListRequest{
		ListRequest: params.ListRequest{
			PartnerId:  partnerId,
			OrderField: "created_at",
		},
	}
	scopes, _, err := s.repoService.ListScope(scopeListReq)
	if len(scopes) == 0 {
		return make([]*HomePageScopeResponse, 0), nil
	}
	var scopeIds = make(map[uint64]bool, len(scopes))
	for _, scope := range scopes {
		scopeIds[scope.Id] = true
	}

	// get all client
	clientListReq := &params.ClientListRequest{
		PartnerId:  partnerId,
		ClientType: enum.WebClient,
		AllScope:   true,
	}
	clients, _, err := s.repoService.ListClient(clientListReq)
	if err != nil {
		return make([]*HomePageScopeResponse, 0), nil
	}
	if len(clients) == 0 {
		return make([]*HomePageScopeResponse, 0), nil
	}

	var scopeId2ClientIdMap = make(map[uint64]string)
	for _, c := range clients {
		if _, ok := scopeIds[c.ScopeId]; ok {
			_, exist := scopeId2ClientIdMap[c.ScopeId]
			if !exist {
				scopeId2ClientIdMap[c.ScopeId] = c.ClientId
			}
		}
	}

	var result = make([]*HomePageScopeResponse, 0)
	for _, scope := range scopes {
		if clientId, ok := scopeId2ClientIdMap[scope.Id]; ok {
			result = append(result, &HomePageScopeResponse{
				ScopeId:   scope.Id,
				ScopeName: scope.Name,
				ClientId:  clientId,
			})
		}
	}
	return result, nil
}
